package com.tul.vapp.servicecenter.util;

import com.tul.cusa.common.util.StringUtil;
import com.tul.vapp.servicecenter.common.DirConstant;

import java.io.File;

/**
 * create by wujunlei 格式化JSON字符串
 *
 * @author wujunlei
 * @since 2018/1/8
 */
public class ConfigJsonUtil {

    /**
     * 格式化输出JSON字符串
     *
     * @param jsonStr jsonStr
     * @return str
     */
    public static String formatJson(String jsonStr) {
        if (StringUtil.isEmpty(jsonStr)) {
            return "";
        }
        int level = 0;
        StringBuffer jsonForMatStr = new StringBuffer();
        for (int i = 0; i < jsonStr.length(); i++) {
            char c = jsonStr.charAt(i);
            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
                jsonForMatStr.append(getLevelStr(level));
            }
            level = handleEachChar(c, jsonForMatStr, level, i, jsonStr);
        }
        return jsonForMatStr.toString();
    }

	/**
     * 处理单个字符
     * @param ch 单个字符
     * @param buffer buffer
     * @param level level
     * @param len 字符串长度
     * @param srcStr 未格式的原始字符串
     * @return level
     */

    public static int handleEachChar(char ch, StringBuffer buffer, int level, int len, String srcStr) {
        switch (ch) {
        case '{':
        case '[':
            buffer.append(ch + "\n");
            level++;
            break;
        case ',':
            if (srcStr.charAt(len - 1) == '"') {
                buffer.append(ch + "\n");
            } else {
                buffer.append(ch);
            }
            break;
        case '}':
        case ']':
            buffer.append("\n");
            level--;
            buffer.append(getLevelStr(level));
            buffer.append(ch);
            break;
        default:
            buffer.append(ch);
            break;
        }
        return level;
    }

    /**
     * 获取缩进格式
     *
     * @param level level
     * @return str
     */
    private static String getLevelStr(int level) {
        StringBuffer levelStr = new StringBuffer();
        for (int levelI = 0; levelI < level; levelI++) {
            levelStr.append("\t");
        }
        return levelStr.toString();
    }

    /**
     * 获取配置导出路径
     *
     * @return String
     */
    public static String getConfigOutputPath() {
        return getGeneratedPrefix() + DirConstant.CONFIG_PATH + File.separator;
    }

    /**
     * 获取导出路径前缀
     *
     * @return String
     */
    public static String getGeneratedPrefix() {
        return DirConstant.OUTPUT_ROOT_PATH + File.separator + SysConfigUtil.getAppName() + File.separator;
    }
}
